﻿// See https://aka.ms/new-console-template for more information
using BeetleX.MQTT;



public class Class1
{

    const int mCount = 100;

    private static Test mATest = new Test(mCount, "A");

    private static Test mA1Test = new Test(mCount, "D");

    private static Test mBTest = new Test(mCount, "B");
    private static Test mB1Test = new Test(mCount, "E");

    private static Test mCTest = new Test(mCount, "C");
    private static Test mC1Test = new Test(mCount, "F");

    private static long mPublish = 0;

    private static long mLastPublish = 0;

    static void Main()
    {

        Task.Run(() => { mATest.Run(); });
        Task.Run(() => { mBTest.Run(); });
        Task.Run(() => { mCTest.Run(); });

        Task.Run(() => { mA1Test.Run(); });
        Task.Run(() => { mB1Test.Run(); });
        Task.Run(() => { mC1Test.Run(); });

        while (true)
        {
            Console.WriteLine($"{DateTime.Now:HH:mm:ss}\t {(mPublish - mLastPublish):###,###,##0}/秒[总发布量:{mPublish:###,###,##0}]");
            mLastPublish = mPublish;
            System.Threading.Thread.Sleep(990);
        }
    }

    public class Test
    {
        public Test(int count, string user)
        {
            mCount = count;
            mUser = user;
        }



        private int mCount;

        private string mUser;

        private Random mRandom = new Random();


        private List<MQTTClient<MQTTParse>> clients = new List<MQTTClient<MQTTParse>>();

        public async Task Run()
        {

            for (int i = 0; i < mCount; i++)
            {
                MQTTClient<MQTTParse> client = new MQTTClient<MQTTParse>($"driver_{mUser}_{i:000}", "localhost", 8089);
                client.ClientInfo.SetUser(mUser, "123456");
                await client.Connect();
                clients.Add(client);
            }
            await Task.Delay(1000);
            while (true)
            {
                int i = 1;
                foreach (var item in clients)
                {
                    await item.PublishJson($"/driver/{mUser}/{i}", 0, CreateData());
                    System.Threading.Interlocked.Increment(ref mPublish);
                    i++;
                }

                System.Threading.Thread.Sleep(1);
            }
        }

        private object CreateData()
        {
            return new { Location = "cn",Value=mRandom.NextDouble() };
        }
    }
}

;
